import { Injectable } from '@nestjs/common'
import { across, bet, tower } from '@prisma/client'
import { PrismaService } from 'src/prisma/prisma.service'
import { calcAngle, calcF, calcFB, calcHi, calcTAFromTB, calcTBFromFB } from 'src/section/utils/ljImageMath'
import { CreateCalculateAcrossDto } from './dto/create-calculate-across.dto'
import { UpdateCalculateAcrossDto } from './dto/update-calculate-across.dto'
import { AcrossCalculate } from './calculate/AcrossCalculate'

interface AcrossCalculateConfig {
  lst_tower: tower[]
  lst_bet: bet[]
  lst_across: across[]
  w: number
  e: number
  orderId: number
}

@Injectable()
export class CalculateAcrossService {
  constructor(private prisma: PrismaService) {}

  async create(createCalculateAcrossDto: CreateCalculateAcrossDto) {
    return await this.prisma.calculateAcross.create({ data: createCalculateAcrossDto })
  }

  // 获取所有的calcAcross
  async findAll(args: Record<string, any>) {
    const { orderId } = args
    return await this.prisma.calculateAcross.findMany({ where: { orderId } })
  }

  // 更新calcAcross
  async update(id: number, updateCalculateAcrossDto: UpdateCalculateAcrossDto) {
    return await this.prisma.calculateAcross.update({
      where: { id },
      data: updateCalculateAcrossDto,
    })
  }

  // 将所有的calcAcross进行排序
  async setRank(args: Record<string, any>) {
    const lst_across = await this.findAll(args)
    // 将集合进行
    lst_across.sort((a1, a2) => a2.TT - a1.TT)
    const res = lst_across.map(async (item, index) => {
      return await this.update(item.id, { rank: index + 1 })
    })
    await Promise.all(res)
  }

  // 计算控制点的受力情况-出口张力
  calculate(config: AcrossCalculateConfig) {
    const { lst_tower, lst_bet, lst_across, w, e, orderId } = config
    const acrossCalculate = new AcrossCalculate(lst_tower, lst_bet, lst_across, w, e)
    // 计算
    const lst_across_force = acrossCalculate.calculate()
    // 排序
    lst_across_force.sort((a1, a2) => a2.TT - a1.TT)
    const lst_across_force_sort = lst_across_force.map((item, index) => ({
      ...item,
      orderId,
      rank: index + 1,
    }))

    return lst_across_force_sort
  }
}
